<?php

namespace App\Services;

use App\Models\ApprovalBookTitle;
use App\Models\ApprovalBorrow;
use App\Models\ApprovalConfig;
use App\Models\ApprovalLog;
use App\Models\PartCompany;
use App\Models\ProjectClassify;
use App\Models\User;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;

class ApprovalService extends OrganizeService
{
    /**
     * 获取类型
     */
    public static function getType()
    {
        return [
            [
                'type'  => 1,
                'title' => '案卷审批'
            ],
            [
                'type'  => 2,
                'title' => '借阅审批'
            ]
        ];
    }

    /**
     * 获取审批人员树状图
     * 多个 orderBy 条件链式操作时，写在前面的优先级高，写在后面的优先级低。
     */
    public function getApprovalUsers()
    {
        $companyId = company_id();
        $list      = ApprovalConfig::query()
            ->where('company_id', $companyId)
            ->select('user_id', 'level', 'type')
            ->orderBy('type')
            ->orderBy('level')
            ->get();

        if ($list->isEmpty()) return [];

        $list = $list->toArray();

        $tempArr = [];
        $typeArr = []; //存放审批类型
        $result  = [];
        foreach ($list as &$val) { //分组，按照分类，再按照审批等级
            $user         = User::query()->select('nickname', 'phone')->find($val['user_id']);
            $val['title'] = $user->nickname . "（{$user->phone}）";

            $tempArr[$val['type']][$val['level']][] = $val;
        }
        foreach ($tempArr as $key2 => $val2) {
            $levelArr = []; //存放审批等级
            foreach ($val2 as $key3 => $val3) {
                $userArr = []; //存放审批用户
                foreach ($val3 as $val4) {
                    $typeArr['type'] = $val4['type']; //追加一个数据，删除某个审批用
                    $arr3['title']   = $val4['title'];
                    $userArr[]       = $arr3;
                }
                $arr2['title']    = config('site')['approval_levels'][$key3];
                $arr2['children'] = $userArr;
                $levelArr[]       = $arr2;
            }
            $typeArr['title']    = config('site')['approval_types'][$key2];
            $typeArr['children'] = $levelArr;
            $result[]            = $typeArr;
        }
        return $result;
    }

    /**
     * 配置审批规则
     * 一个公司指定审批类型的某个审批级别只允许有一个
     */
    public function setRule($params)
    {
        try {
            $type           = $params['type'];
            $level          = $params['level'];
            $userIds        = is_array($params['user_ids']) ? $params['user_ids'] : to_array($params['user_ids']);
            $companyId      = company_id();
            $map            = [
                'company_id' => $companyId, //当前用户所属公司id
                'type'       => $type,
                'level'      => $level, //审批级别
            ];
            $approvalConfig = ApprovalConfig::query()->where($map)->first();
            if ($approvalConfig) throw new Exception('该类型审核等级已存在');
            /**
             * 判断该用户是否已添加到这个类型的其他审核等级，
             * 例如张三已经被添加为 分类审批第2级，那么就不允许再把他添加为第3级
             **/
            foreach ($userIds as $userId) {
                $info = ApprovalConfig::query()->where([
                    'company_id' => $companyId,
                    'type'       => $type,
                    'user_id'    => $userId, //选定的用户
                ])->first();
                if (!empty($info)) {
                    $nickname = User::query()->where('id', $userId)->value('nickname');
                    throw new Exception($nickname . '已添加过！用户不可参与同类型不同等级审批');
                } else {
                    $approvalConfig             = new ApprovalConfig();
                    $approvalConfig->company_id = $companyId;
                    $approvalConfig->type       = $type;
                    $approvalConfig->user_id    = $userId;
                    $approvalConfig->level      = $level;
                    $approvalConfig->creator_id = user_id();
                    $approvalConfig->save();
                }
            }
            CommonService::addActionLog('配置审批规则', "类型：{$type}, 等级：{$level}");
            return ['msg' => ''];
        } catch (Exception $exception) {
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 删除配置的审批规则
     */
    public function delApprovalRule($type)
    {
        $companyId = company_id();

        CommonService::addActionLog('删除审批规则', "类型：{$type}");

        return ApprovalConfig::query()
            ->where('company_id', $companyId)
            ->where('type', $type)
            ->delete();
    }

    /**
     * 获取当前审批内容的最大审批等级
     */
    public function getMaxLevel($type)
    {
        return ApprovalConfig::query()
            ->where('company_id', company_id())
            ->where('type', $type)
            ->max('level');
    }

    /**
     * 获取当前登录用户指定类型的的审批等级
     */
    public function getUserApprovalLevel($type)
    {
        $level = ApprovalConfig::query()
            ->where('company_id', company_id())
            ->where('user_id', user_id())
            ->where('type', $type)
            ->value('level');

        return $level ?: 0;
    }

    /**
     * 如果这个类型的等级有 三个人审批，判断是否全部审批
     */
    public function isAllHadApproval($type, $level, $targetId)
    {
        $configUserCount = ApprovalConfig::query()  //获取配置人数
        ->where('company_id', company_id())
            ->where('type', $type)
            ->where('level', $level)
            ->count();

        $hadApprovalCount = ApprovalLog::query() //已审批记录人数
        ->where('company_id', company_id())
            ->where('type', $type)
            ->where('level', $level)
            ->where('target_id', $targetId)
            ->count();

        return $configUserCount == $hadApprovalCount; //相等true; 不相等false
    }

    /**
     * 获取【案卷审批数据】
     */
    public function getApprovalBookTitles($request, $perPage)
    {
        $baseQuery = ApprovalBookTitle::query();

        if ($request->filled('keyword')) {
            $keyword = $request->input('keyword');
            $baseQuery->where('creator_name', 'like', "%{$keyword}%");
        }
        if ($request->filled('date_range')) {
            $dateRange = $request->input('date_range');
            $baseQuery->whereBetween('created_at', $dateRange);
        }
        if ($request->filled('status')) {
            $status = $request->input('status');
            $baseQuery->where('status', '=', $status);
        }
        $list = $baseQuery
            ->select('id', 'project_name', 'part_company_id', 'part_company_name', 'project_classify_name',
                'content', 'creator_name', 'created_at', 'status')
            ->orderByDesc('id')
            ->paginate($perPage);

        if ($list->isEmpty()) return [];

        return $this->removeNoUsedPageParams($list->toArray());
    }

    /**
     * 获取【案卷审批】案卷数据
     */
    public function getBookTitleList($bookTitleApprovalId, $perPage, $keyword)
    {
        $approvalBookTitle = ApprovalBookTitle::query()->where('id', $bookTitleApprovalId)->first();

        $bookTitleIds = explode(',', $approvalBookTitle->book_title_ids); //哪些数据

        $bookTitleInstance = $this->getBookTitleInstance($approvalBookTitle->part_company_id, $approvalBookTitle->project_classify_id);

        $list = $bookTitleInstance
            ->whereIn('id', $bookTitleIds)
            ->when($keyword, function ($query) use ($keyword) {
                $query->where('title', 'like', "%{$keyword}%");
            })
            ->paginate($perPage);

        if ($list->isEmpty()) return [];

        return $this->removeNoUsedPageParams($list->toArray());
    }

    /**
     * 获取【案卷审批】卷内数据
     */
    public function getBookCatalogList($partCompanyId, $projectClassifyId, $bookTitleId, $request, $limit = 10)
    {
        $bookCatalogInstance = $this->getBookCatalogInstance($partCompanyId, $projectClassifyId);
        $baseQuery           = $bookCatalogInstance->where('book_title_id', $bookTitleId);
        if ($request->filled('keyword')) {
            $keyword = $request->input('keyword');
            $baseQuery->where('title', 'like', "%{$keyword}%");
        }
        $list = $baseQuery
            ->select('id', 'serial_no', 'title', 'file_number', 'director', 'page_num', 'c_date', 'is_pic', 'remark')
            ->paginate($limit);

        if ($list->isEmpty()) return [];

        return $this->removeNoUsedPageParams($list->toArray());
    }

    /**
     * 提交【案卷审批】数据
     * status ： 0核对中, 1待审核, 2通过, 3拒绝
     */
    public function submitBookTitleApprovalData($partCompanyId, $projectClassifyId, $bookTitleIds)
    {
        DB::beginTransaction();
        try {
            $bookTitleInstance = $this->getBookTitleInstance($partCompanyId, $projectClassifyId);
            $baseQuery         = $bookTitleInstance->where('project_classify_id', $projectClassifyId);
            $bookTitleIds      = to_array($bookTitleIds);
            $selectAll         = empty($bookTitleIds) ? 1 : 0;
            if (!$selectAll) {
                if (empty($bookTitleIds)) {
                    throw new Exception('不可以提交空数据！');
                }
                $baseQuery->whereIn('id', $bookTitleIds); //如果没全选，按照指定
            }
            if ($selectAll) { //下面写入审批数据记录表
                $bookTitleIds = $baseQuery->pluck('id');
                if ($bookTitleIds->isEmpty()) {
                    throw new Exception('不可以提交空数据！');
                }
                $bookTitleIds = $bookTitleIds->toArray();
            }
            $baseQuery->update(['status' => 1]); //改变状态
            $content = CommonService::getProjectContent($partCompanyId, $projectClassifyId);
            $count                                    = count($bookTitleIds);
            $ApprovalBookTitle                        = new ApprovalBookTitle();
            $ApprovalBookTitle->part_company_id       = $partCompanyId;
            $ApprovalBookTitle->project_name          = $content['project'];
            $ApprovalBookTitle->part_company_name     = $content['part_company'];
            $ApprovalBookTitle->project_classify_id   = $projectClassifyId;
            $ApprovalBookTitle->project_classify_name = $content['classify'];
            $ApprovalBookTitle->creator_id            = user_id();
            $ApprovalBookTitle->creator_name          = user()->nickname;
            $ApprovalBookTitle->content               = "提交了【{$count}】条案卷目录";
            $ApprovalBookTitle->book_title_ids        = implode(',', $bookTitleIds); //本次提交了那些数据
            $ApprovalBookTitle->status                = 1;
            $ApprovalBookTitle->save();

            $userIds = $this->getApprovalConfigUserIds(1, 1); //添加消息记录
            foreach ($userIds as $userId) {
                MessageService::addNewLog(2, '有新的案卷审批', $ApprovalBookTitle->id, $userId);
            }
            CommonService::addProjectActionLog("提交案卷审批", $ApprovalBookTitle->id, $partCompanyId, $projectClassifyId);

            DB::commit();
            return ['msg' => ''];
        } catch (Exception $exception) {
            DB::rollBack();
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 获取指定审批等级的人
     * $type 1案卷审批，2借阅审批
     */
    public function getApprovalConfigUserIds($type, $level)
    {
        return ApprovalConfig::query()
            ->where('type', $type)
            ->where('level', $level)
            ->pluck('user_id')
            ->toArray();
    }

    /**
     * 【案卷审批】操作
     * $ids 需要审批操作的数据 ids,数组或逗号分割的字符串
     * $type 审批的类型，1案卷审批，2借阅审批
     * $status 1通过，2拒绝
     */
    public function bookTitleApprovalAction($params)
    {
        DB::beginTransaction();
        try {
            $type                = 1; //案卷审批
            $status              = $params['status'];
            $bookTitleApprovalId = $params['book_title_approval_id'];
            $approvalBookTitle   = ApprovalBookTitle::query()->where('id', $bookTitleApprovalId)->first();
            if (!in_array($status, [1, 2])) {
                throw new Exception('参数错误！');
            }
            if ($approvalBookTitle->status) {
                throw new Exception('已审批完毕！');
            }
            $userApprovalLevel = $this->getUserApprovalLevel($type); //当前用户审批等级
            if (!$userApprovalLevel) {
                throw new Exception('您无权审批~');
            }
            $maxLevel      = $this->getMaxLevel($type); //最大审批等级
            $approvalLevel = $approvalBookTitle->approval_level; //已进行到的审批等级
            if ($approvalLevel < $maxLevel) {
                $this->writeApprovalLog($bookTitleApprovalId, $userApprovalLevel, $type);
                if ($this->isAllHadApproval($type, $userApprovalLevel, $bookTitleApprovalId)) { //配置人员全部审批
                    $approvalBookTitle->increment('approval_level'); //审批等级 +1
                    if ($approvalLevel + 1 == $maxLevel) { //如果是最后审批
                        $approvalBookTitle->update(['status' => $status]);
                        MessageService::addNewLog(2, '您提交的案卷审批结束', $approvalBookTitle->id, $approvalBookTitle->creator_id);
                    } else {
                        $userIds = $this->getApprovalConfigUserIds(1, $approvalLevel + 1); //接下来该谁审批
                        foreach ($userIds as $userId) {
                            MessageService::addNewLog(2, '有新的案卷审批', $approvalBookTitle->id, $userId);
                        }
                    }
                }
            }
            CommonService::addProjectActionLog('案卷审批操作', $bookTitleApprovalId, $approvalBookTitle->part_company_id, $approvalBookTitle->project_classify_id);
            DB::commit();
            return ['msg' => ''];
        } catch (Exception $exception) {
            DB::rollBack();
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 写入审批记录
     */
    public function writeApprovalLog($targetId, $level, $type)
    {
        $approvalLog             = new ApprovalLog();//写入审批记录
        $approvalLog->company_id = company_id();
        $approvalLog->user_id    = user_id();
        $approvalLog->type       = $type;
        $approvalLog->target_id  = $targetId;
        $approvalLog->level      = $level;

        return $approvalLog->save();
    }

    /**
     * 提交【借阅审批】数据
     * type ：1案卷，2卷内
     * type=1，$ids 代表案卷id; type=2时，代表卷内id
     */
    public function submitBorrowApprovalData($params)
    {
        DB::beginTransaction();
        try {
            info($params);
            $submitDetail      = self::getSubmitDetail($params);
            $partCompanyId     = $submitDetail['part_company_id'];
            $projectClassifyId = $submitDetail['project_classify_id'];
            $selectCon         = $submitDetail['select_con'];
            $formData          = $params['form_data'];

            $content = CommonService::getProjectContent($partCompanyId, $projectClassifyId);

            $approvalBorrow                        = new ApprovalBorrow();
            $approvalBorrow->part_company_id       = $partCompanyId;
            $approvalBorrow->project_name          = $content['project'];
            $approvalBorrow->part_company_name     = $content['part_company'];
            $approvalBorrow->project_classify_id   = $projectClassifyId;
            $approvalBorrow->project_classify_name = $content['classify'];
            $approvalBorrow->creator_id            = user_id();
            $approvalBorrow->creator_name          = user()->nickname;
            $approvalBorrow->content               = "案卷借阅请求";
            $approvalBorrow->type                  = 1;
            $approvalBorrow->select_all            = $params['ids'] ? 0 : 1;
            $approvalBorrow->ids                   = $params['ids'] ? json_encode($selectCon) : ''; //本次提交了那些数据
            $approvalBorrow->status                = 0; //待审核
            $approvalBorrow->expire_time           = now()->addDays(30)->toDateString(); //默认30天后过期
            $approvalBorrow->is_online             = $formData['is_online'] ?? 1;
            $approvalBorrow->borrow_type           = $formData['borrow_type'] ?? 1;
            $approvalBorrow->borrow_date           = format_str($formData['borrow_date']); //借阅日期
            $approvalBorrow->borrow_unit           = format_str($formData['borrow_unit']); //借阅单位
            $approvalBorrow->borrow_user           = format_str($formData['borrow_user']); //借阅人
            $approvalBorrow->borrow_mobile         = format_str($formData['borrow_mobile']); //借阅人手机号
            $approvalBorrow->borrow_uses           = format_str($formData['borrow_uses']); //借阅用途
            $approvalBorrow->archives_pos          = format_str($formData['archives_pos']); //档案所在位置
            $approvalBorrow->plan_return_date      = date('Y-m-d', strtotime($formData['plan_return_date'])); //预计归还时间

            $approvalBorrow->save();

            $userIds = $this->getApprovalConfigUserIds(2, 1); //添加消息记录
            foreach ($userIds as $userId) {
                MessageService::addNewLog(3, '有新的借阅审批', $approvalBorrow->id, $userId);
            }
            CommonService::addProjectActionLog("提交借阅审批", $approvalBorrow->id, $partCompanyId, $projectClassifyId);
            DB::commit();
            return ['msg' => '', 'id' => $approvalBorrow->id];
        } catch (Exception $exception) {
            DB::rollBack();
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 获取提交的格式化后的信息
     * @author: lxk
     * @date: 2023/5/29 15:24
     */
    public static function getSubmitDetail($params)
    {
        $selectAll = $params['ids'] ? 0 : 1;
        $selectCon = [];
        if ($params['submit_from'] == 1) { //如果按照参建单位
            if ($selectAll) { //全选
                $projectClassifyIds = ProjectClassifyService::getProjectClassifyIds($params['part_company_id']);
            } else { //指定
                $dataList = $params['ids'];
                foreach ($dataList as $val) {
                    $rowData = json_decode($val, true);
                    $arr['p_com_id'] = $rowData['part_company_id'];
                    $arr['p_cla_id'] = $rowData['project_classify_id'];
                    $arr['b_tit_id'] = $rowData['id'];
                    $selectCon[]     = $arr;
                }
                $projectClassifyIds = array_unique(array_column($selectCon, 'p_cla_id'));
            }
            return [
                'part_company_id'     => $params['part_company_id'],
                'project_classify_id' => $projectClassifyIds[0],
                'select_con'          => $selectCon,
                'data_count'          => count($selectCon),
            ];
        } else {  //如果按照参项目分类检索
            if ($selectAll) { //全选
                $partCompanyIds = self::getPartCompanyIds($params['project_id']); //获取用户当前能看的项目下的参见单位
            } else { //指定
                $dataList = $params['ids'];
                foreach ($dataList as $val) {
                    $rowData = json_decode($val, true);
                    $arr['p_com_id'] = $rowData['part_company_id'];
                    $arr['p_cla_id'] = $rowData['project_classify_id'];
                    $arr['b_tit_id'] = $rowData['id'];
                    $selectCon[]     = $arr;
                }
                $partCompanyIds = array_unique(array_column($selectCon, 'p_com_id'));
            }
            return [
                'part_company_id'     => $partCompanyIds[0],
                'project_classify_id' => $params['project_classify_id'],
                'select_con'          => $selectCon,
                'data_count'          => count($selectCon),
            ];
        }
    }

    /**
     * 用户能看到的参建范围
     *
     * @param $projectId
     * @param int $ptType
     * @return array
     * @author: lxk
     * @date: 2025-01-11 11:43
     */
     public static function getPartCompanyIds($projectId,int $ptType = 0) : array
     {
         $thisQuery = PartCompany::query()
             ->when($ptType, function($query) use ($ptType) {
                 return $query->where('type', $ptType);
             })
             ->where('project_id', $projectId);

         if (is_super_admin() || is_company_admin()) { // 超管和公司管理员能看全部
             return $thisQuery->pluck('id')->toArray();
         }
         $partCompanyUser = ProjectService::partCompanyUser($projectId); //用户在项目中属于那种参见单位类型
         if(!$partCompanyUser) return [];
         if ($partCompanyUser['type'] == 2) { //监理 可以看自己所在的监理单位和匹配的施工单位
             $partCompanyId = $partCompanyUser['part_company_id'];
             $matchUnits    = PartCompany::query()->where('id', $partCompanyId)->value('match_units');
             $matchUnits    = to_array($matchUnits);
             array_push($matchUnits, $partCompanyId); //自己+自己能看的施工单位ids
             $thisQuery->whereIn('id', $matchUnits);
         }
         elseif ($partCompanyUser['type'] == 3) { //施工单位只看到自己
             $thisQuery->where('id', $partCompanyUser['part_company_id']);
         }
         $partCompanyIds = $thisQuery->pluck('id');
         if ($partCompanyIds->isEmpty()) return [];

         return $partCompanyIds->toArray();
     }

    /**
     * 【借阅审批】
     * $ids 需要审批操作的数据 ids,数组或逗号分割的字符串
     * $type 审批的类型，1分类审批，2...
     * $status 1通过，2拒绝
     */
    public function borrowApprovalAction($params)
    {
        DB::beginTransaction();
        try {
            $type             = 2; //借阅审批
            $status           = $params['status'];
            $refuseReason     = $params['refuse_reason'] ?? '';
            $approvalBorrowId = $params['approval_borrow_id'];
            $approvalBorrow   = ApprovalBorrow::query()->find($approvalBorrowId);
            if (!in_array($status, [1, 2])) {
                throw new Exception('参数错误！');
            }
            if ($approvalBorrow->status) {
                throw new Exception('已审批完毕！');
            }
            $userApprovalLevel = $this->getUserApprovalLevel($type); //当前用户审批等级
            if (!$userApprovalLevel) {
                throw new Exception('您无权审批~');
            }
            if ($status == 2) { //如果有人拒绝，审批结束
                $approvalBorrow->status        = $status;
                $approvalBorrow->refuse_reason = $refuseReason;
                $approvalBorrow->save();
            } else {
                $maxLevel      = $this->getMaxLevel($type); //最大审批等级
                $approvalLevel = $approvalBorrow->approval_level; //已进行到的审批等级
                if ($approvalLevel < $maxLevel) {
                    $this->writeApprovalLog($approvalBorrowId, $userApprovalLevel, $type);
                    if ($this->isAllHadApproval($type, $userApprovalLevel, $approvalBorrowId)) { //配置人员全部审批
                        $approvalBorrow->increment('approval_level');
                        if ($approvalLevel + 1 == $maxLevel) { //如果是最后审批
                            $systemConfig                = SystemConfigService::getInfo();
                            $borrowExpire                = $systemConfig['borrow_expire'] ?: 15; //如果系统没有配置，默认15天
                            $approvalBorrow->status      = $status;
                            $approvalBorrow->expire_time = $status;
                            Carbon::parse("+{$borrowExpire} days")->toDateTimeString(); //过期时间,大于这个时间意味着无法查看
                            $approvalBorrow->save();
                        } else {
                            $userIds = $this->getApprovalConfigUserIds(2, $approvalLevel + 1); //接下来该谁审批
                            foreach ($userIds as $userId) {
                                MessageService::addNewLog(3, '有新的借阅审批', $approvalBorrow->id, $userId);
                            }
                        }
                    }
                }
            }
            CommonService::addProjectActionLog("借阅审批操作", $approvalBorrowId, $approvalBorrow->part_company_id, $approvalBorrow->project_classify_id);
            DB::commit();
            return ['msg' => ''];
        } catch (Exception $exception) {
            DB::rollBack();
            return ['msg' => $exception->getMessage()];
        }
    }

    /**
     * 获取【借阅审批】数据
     */
    public function getBorrowsData($request, $limit)
    {
        $baseQuery = ApprovalBorrow::query();
        if ($request->filled('keyword')) {
            $keyword = $request->input('keyword');
            $baseQuery->where('creator_name', 'like', "%{$keyword}%");
        }
        if ($request->filled('date_range')) {
            $dateRange = $request->input('date_range');
            $baseQuery->whereBetween('created_at', $dateRange);
        }
        if ($request->filled('status')) {
            $status = $request->input('status');
            $baseQuery->where('status', '=', $status);
        }
        $list = $baseQuery
            ->select('id', 'is_online', 'borrow_type', 'project_name', 'part_company_id', 'part_company_name', 'project_classify_name',
                'content', 'creator_name', 'expire_time', 'created_at', 'status', 'refuse_reason'
            )
            ->orderByDesc('id')
            ->paginate($limit);

        if ($list->isEmpty()) return [];

        foreach ($list['data'] as &$val) {
            $val['is_online_text'] = $val['is_online'] == 1 ? '线上' : '线下';
        }

        return $this->removeNoUsedPageParams($list->toArray());
    }

    /**
     * 获取【借阅审批】案卷数据
     */
    public function getBorrowBookTitleList($approvalBorrow, $request, $limit)
    {
        $bookTitleInstance   = $this->getBookTitleInstance($approvalBorrow->part_company_id, $approvalBorrow->project_classify_id);
        $bookCatalogInstance = $this->getBookCatalogInstance($approvalBorrow->part_company_id, $approvalBorrow->project_classify_id);

        $ids = explode(',', $approvalBorrow->ids);
        if ($approvalBorrow->type == 2) {
            $bookTitleId = $bookCatalogInstance->where('id', $ids[0])->value('book_title_id');
            $ids = [$bookTitleId];
        }
        $baseQuery = $bookTitleInstance->whereIn('id', $ids);
        if ($request->filled('keyword')) {
            $keyword = $request->input('keyword');
            $baseQuery->where('title', 'like', "%{$keyword}%");
        }
        $list = $baseQuery->paginate($limit);

        if ($list->isEmpty()) return [];

        return $this->removeNoUsedPageParams($list->toArray());
    }


}
